package cn.pomelo.secondskill.rabbitMQ;

import cn.pomelo.secondskill.common.Constants;
import cn.pomelo.secondskill.exception.SecondsKillException;
import cn.pomelo.secondskill.model.Orders;
import cn.pomelo.secondskill.rabbitMQ.domain.MessageEvent;
import cn.pomelo.secondskill.service.OrdersService;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class Receiver {

    @Resource
    private OrdersService ordersService;

    /**
     * 秒杀订单
     *
     * @param event
     * @throws SecondsKillException
     */
    @RabbitHandler
    @RabbitListener(queuesToDeclare = @Queue(Constants.SECONDS_KILL_ORDER_QUEUE))
    public void kill(MessageEvent event) throws SecondsKillException {
        System.out.println(event);
        Orders data = (Orders) event.getData();
        Orders orders = ordersService.selectByPrimaryKey(data.getId());
        int key ;
        if (orders == null) {
            key = ordersService.insert((Orders) event.getData());
        } else {
            key = ordersService.updateByPrimaryKey(data);
        }
        if (key < 0) {
            throw new SecondsKillException("秒杀失败！");
        }
    }

    /**
     * 加入购物车
     *
     * @param event
     * @throws SecondsKillException
     */
    @RabbitHandler
    @RabbitListener(queuesToDeclare = @Queue(Constants.SECOND_KILL_CAR_QUEUE))
    public void car(MessageEvent event) throws SecondsKillException {
        int insert = ordersService.insert((Orders) event.getData());
        if (insert < 0) {
            throw new SecondsKillException("加入购物车失败！");
        }
    }
}
